<?php
namespace app\controller;
use app\BaseController;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;
class User extends BaseController
{
    public function profile()
{
    $token = Request::header('Authorization');
    if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
        return json(['code' => 401, 'msg' => '未授权访问']);
    }
    $token = $matches[1];
    $user = Db::name('think_user')->where('token', $token)->find();
    if (!$user) {
        return json(['code' => 401, 'msg' => '无效token']);
    }
    return json([
        'code' => 200,
        'msg'  => '获取成功',
        'data' => [
            'avatar'   => $user['avatar'],
            'nickname' => $user['nickname'],
            'phone'    => $user['mobile']
        ]
    ]);
}
    public function update()
{
    $token = Request::header('Authorization');
    if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
        return json(['code' => 401, 'msg' => '未授权访问']);
    }
    $token = $matches[1];
    $user = Db::name('think_user')->where('token', $token)->find();
    if (!$user) {
        return json(['code' => 401, 'msg' => '无效token']);
    }
    $userId = $user['id'];

    $avatar = $this->request->post('avatar');
    $nickname = $this->request->post('nickname');
    $mobile = $this->request->post('mobile');
    $file = $this->request->file("file");
    // 处理头像文件上传
    $updateData = [];
    if ($file) {
        $savename = Filesystem::disk('public')->putFile('avatar', $file);
        if ($savename) {
            $avatarUrl = "https://www.pfjsg.cn" . '/storage/' . $savename;
            $updateData['avatar'] = $avatarUrl;
        } else {
            return json(['code' => 500, 'msg' => '头像上传失败']);
        }
    } else {
        // 兼容直接传url的情况
        $avatar = $this->request->post('avatar');
        if ($avatar !== null) $updateData['avatar'] = $avatar;
    }
    if ($nickname !== null) $updateData['nickname'] = $nickname;
    if ($mobile !== null) $updateData['mobile'] = $mobile;

    if (empty($updateData)) {
        return json(['code' => 400, 'msg' => '没有需要更新的内容']);
    }

    Db::name('think_user')->where('id', $userId)->update($updateData);

    return json(['code' => 200, 'msg' => '更新成功']);
}
}